#include <cmtproto.h>

bool CmdParser::reset(char *ptr)
{
    char *end;

    _buf = NULL;

    if (str_get_escape_str_until(ptr, ':', _cmd, 128, &end) < 0
        || *end != ':')
        return false;

    _buf = end + 1;

    str_lrtrim(_cmd);

    if (_cmd[0] == 0)
        return false;

    return true;
}

bool CmdParser::next()
{
    char *end;

    if (_buf == NULL || *_buf == 0)
        return false;

    if (str_get_escape_str_until(_buf, '=', _key, 128, &end) < 0
        || *end != '=')
        return false;

    str_lrtrim(_key);

    _buf = end + 1;

    if (str_get_escape_str_until(_buf, ';', _value, 1024, &end) < 0
        || *end != ';')
        return false;

    _buf = end + 1;

    str_lrtrim(_key);
    str_lrtrim(_value);

    if (_key[0] == 0)
        return false;

    return true;
}

int InputReceiver::receive_data(int fd) {
    int buf_free_size, r, total_read = 0;

    for (;;) {
        if (_cur_pos >= _cap_size)
            expand_buffer();

        buf_free_size = _cap_size - _cur_pos;

        r = recv(fd, _buf + _cur_pos, buf_free_size, MSG_DONTWAIT);
        if (r > 0) {
            _cur_pos += r;
            total_read += r;
            if (r < buf_free_size)
                break;
        }
        else if (r == 0) {
            _socket_status = SS_CLOSED;
            break;
        }
        else {
            if (errno != EAGAIN && errno != EINTR)
                _socket_status = SS_EXCEPTION;
            break;
        }
    }

    return total_read;
}
